import React, { useEffect, useRef, useState } from 'react';
import microApp from '@micro-zoe/micro-app';
import { APP_MODE } from 'ice';

interface MicroAppProps {
  /**
   * 网页URL
   */
  url: string;
  /**
   * 网页名称（可选）
   */
  name?: string;
  /**
   * 渲染的组件ID
   */
  compId?: string;
  /**
   * 是否使用iframe嵌入网页（可选）
   */
  iframe?: boolean;
  /**
   * 是否禁用网页的scope样式（可选）
   */
  disableScopecss?: boolean;
  /**
   * 是否保持网页在内存中不被销毁（可选）
   */
  keepAlive?: boolean;
  /**
   * 其他配置项
   */
  [key: string]: any;
}

let appIndex = 0;

// 每个 url 有个唯一的前缀
const cache: Record<string, string> = {};
function getName(url: string, name?: string) {
  const idx = ++appIndex;

  if (!cache[url]) {
    cache[url] = `Url-Prefix${idx}-`;
  }
  if (!name) {
    // eslint-disable-next-line no-param-reassign
    name = `app-${idx}`;
  }
  return cache[url] + name;
}

function MicroApp(props: MicroAppProps) {
  const { url, name, compId, iframe, disableScopecss, keepAlive, ..._props } = props;

  const [ready, setReady] = useState(false);
  const nameRef = useRef('');

  // 构造唯一ID
  useEffect(() => {
    nameRef.current = getName(url, name);
    setReady(true);

    return () => {
      setReady(false);
    };
  }, [url, name]);

  // 监听参数变化，向下传参
  useEffect(() => {
    microApp.setData(nameRef.current, {
      id: compId, // 应用id
      data: _props as any, // 应用数据
    });
  }, [compId, _props]);

  return ready ? (
    <micro-app
      name={nameRef.current!}
      url={url}
      clear-data
      disable-memory-router
      fiber
      inline={APP_MODE !== 'prod'}
      iframe={iframe}
      disableScopecss={disableScopecss}
      keepAlive={keepAlive}
    />
  ) : (
    <></>
  );
}

export default MicroApp;
